#include "chat.h"
#include "ui_chat.h"
#include <QThread>
#include <QTcpSocket>
#include <QHostAddress>
#include <QInputDialog>
#include <QTimer>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQuery>
#include "myclient.h"
#include <QSqlError>
#include <QVBoxLayout>

Chat::Chat(QWidget *parent,QString uid,QString name) :
    QWidget(parent),uid(uid),name(name),
    ui(new Ui::Chat)
{
    ui->setupUi(this);
    this->setWindowTitle("OpenChatRoom");
    this->setFixedSize(850,500);
    //设置透明度
    ui->scrollArea->setStyleSheet("background: rgba(255, 255, 255, 75);");//最后一位设置透明度0为全透明
    ui->pushButton->setStyleSheet("background: rgba(255, 255, 255, 85);");
    ui->textEdit_2->setStyleSheet("background: rgba(255, 255, 255, 80);");
    QFont font = ui->textEdit->font();
    font.setPointSize(14);
    ui->textEdit->setFont(font);
    //设置背景
    QPixmap pix=QPixmap(":/source/zu.jpg").scaled(this->size());//设置大小
    QPalette palette;
    palette.setBrush(QPalette::Window,QBrush(pix));//QPalette::Background
    this->setPalette(palette);
    //显示好友列表和公共聊天室
    //查询好友的id-可以同时联表查询name，现在暂时没有
    QSqlQuery query;
    query.prepare(  "SELECT"
                        "CASE"
                            "WHEN User_id1 = :user_id1 THEN User_id2"
                            "ELSE User_id1"
                        "END AS Related_User_id"
                    "FROM Friend"
                    "WHERE User_id1 = :user_id1 OR User_id2 = :user_id1;"
    );
    query.bindValue(":user_id1", uid);
    query.exec();
    int pushbotton_id=0;
    QSqlQuery query1;
    while (query.next()) {
        pushbotton_id++;
        QString f_id = query.value(0).toString();
        qDebug() << "ID:"<< f_id;
        //查询ID对应的name
        query1.prepare("select Name from User where Uid= :uid_f");
        query1.bindValue(":uid_f", f_id);
        query1.exec();
        if(query1.next()){//必须使用next才能读取数据
            QString f_name=query1.value(0).toString();
            qDebug() << f_name;
            //创建按钮
            QPushButton *newButton = new QPushButton(f_name, this);//按钮上显示的文字
            newButton->setGeometry(10, 50+pushbotton_id*40, 130, 40);
            QVBoxLayout *layout = new QVBoxLayout();
            layout->addWidget(newButton);

            //绑定按钮，点击按钮清空聊天框(暂时)，绑定当前聊天者的id
//            connect(newButton, &QPushButton::clicked, this, []() {
//                //新建聊天界面并展示
//                //考虑如何隐藏？
//            });
        }
        //聊天记录保存在本地，不是公用一个聊天框，而是隐藏和展示的关系
        //发送的消息保存在本地和服务器，每次进入程序会与远程服务器同步，暂时使用mysql
        //所以这里不用socket连接，使用的是插入和读取数据库的操作
    }

    QThread* t=new QThread;
    MyClient* worker=new MyClient;
    worker->moveToThread(t);//用于发送消息的实例worker放入子线程

    //点击按钮触发startConnect信号启动worker子线程的connectServer函数？
    connect(this,&Chat::startConnect,worker,&MyClient::connectServer);
    //connectOK信号触发时表示连接成功
    connect(worker,&MyClient::connectOK,this,[=](){
        QMessageBox::information(this,"连接服务器","成功连接到服务器");
    });
    connect(worker,&MyClient::gameover,this,[=](){
        QMessageBox::critical(this,"连接服务器失败","无法连接到服务器");
        //释放资源
        t->quit();
        t->wait();
        worker->deleteLater();
        t->deleteLater();
    });

    connect(this,&Chat::sendmsg,worker,&MyClient::sendm);
    //收到发送消息的信号
    connect(worker,&MyClient::mmsend,this,[=](){

    });
    //收到消息的信号
    connect(worker,&MyClient::mmrecived,this,[=](QString data){
        ui->textEdit->append(data);
        qDebug()<<data;
    });

    t->start();
}
Chat::~Chat()
{
    delete ui;
}

void Chat::on_pushButton_2_clicked()
{//加入聊天，连接到服务器
    emit startConnect(port,ip);
}


void Chat::on_pushButton_clicked()
{
    //发送消息
    QString message=ui->textEdit_2->toPlainText();
    //将名字封装到消息中
    QString name_msg=name+':'+message;
    QByteArray data = name_msg.toUtf8();
    qDebug()<<data;
    qDebug()<<"发送消息";
    emit sendmsg(data);
}


void Chat::on_pushButton_3_clicked()
{
    //添加好友
    //读取文本框中内容
    QString friend_uid=ui->lineEdit->text();
    QSqlQuery query;
    query.prepare("INSERT INTO Friend (User_id1, User_id2,status) VALUES (:user_id1, :user_id2,'accepted')");
    if(uid>friend_uid){
        query.bindValue(":user_id1", uid);
        query.bindValue(":user_id2", friend_uid);
    }else{
        query.bindValue(":user_id1", friend_uid);
        query.bindValue(":user_id2", uid);
    }
    if (!query.exec()) {
        //没有查到对应uid
        QMessageBox::critical(this, "Error", "没有查到对应uid或已经添加");
        qDebug() << "Error inserting into table: " << query.lastError().text();
    } else {
        //添加好友成功
        QMessageBox::information(this, "Success", "添加成功");
        ui->lineEdit->clear();
        qDebug() << "Insertion successful.";
        //返回好友关系的uid
        int insertedId = query.lastInsertId().toInt();
//        QSqlQuery query_2;
//        query_2.prepare("select ID from Friend where User_id1=:user_id1 User_id2=:user_id2");
//        query_2.bindValue(":user_id1", uid);
//        query_2.bindValue(":user_id2", friend_uid);
        //创建好友之间的消息表
        QString tableName = "Message_" + QString::number(insertedId);
        QSqlQuery query_3;
        query_3.prepare("CREATE TABLE" + tableName + " "
                        "(ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
                        "Message VARCHAR(30) NOT NULL"
                        ");"
        );
        if (!query_3.exec()) {
            qDebug() << "Table creation failed:" << query_3.lastError().text();
        }
    }
}

